﻿function Guid2(callback) {
	var _url = ip_req || 'http://192.168.9.3:91/';
    $.ajax({
            url: _url + 'ZHFZ/ZHFZService.svc/GetGUID',
            type: 'get',
            dataType: 'jsonp',
        })
        .done(function(res) {
            callback.call(this, res);
        });

}

function showErro(msg) {
	if (msg != null && msg.indexOf("发生未知错误") == 0) {
		console.log(msg);
		return;
	}
	if (msg != null && msg != '') {
		console.log(msg);
		api.alert({
			title : '出错啦！',
			msg : msg
		});
	}
}

function showMsg(msg) {
	if (msg != null && msg != '')
		api.alert({
			title : '提示',
			msg : msg
		});
}

function showSaveProgress() {
	api.showProgress({
		style : 'default',
		animationType : 'fade',
		title : '正在保存',
		text : '请稍等...',
		modal : false
	});
}

function getCookie(keyName) {
	var rlt = $api.getStorage(keyName);
	return rlt;
}

function setCookie(keyName, str) {
	$api.setStorage(keyName, str);
}

function request(url, paras) {
	var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
	var paraObj = {}
	for ( i = 0; j = paraString[i]; i++) {
		paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
	}
	var returnValue = paraObj[paras.toLowerCase()];
	if ( typeof (returnValue) == "undefined") {
		return "";
	} else {
		return returnValue.replace("#", "");
	}
}

function Guid(num) {
	if (num == null) {
		num = 1;
	}
	var guidList = null;
	var filter = "num <= " + num + "";
	getRecordsByFilter("prj", "vwGuid", filter, function(res) {
		if (res != null && res.record.length > 0) {
			guidList = [];
			for (var i = 0; i < res.record.length; i++) {
				guidList.push(res.record[i].id);
			}
		}

	}, showErro, false);
	if (num == 1 && guidList != null && guidList.length > 0) {
		return guidList[0];
	}
	return guidList;
}

function getLocaleDatetime() {
	var objD = new Date();
	var yy = objD.getYear();
	if (yy < 1900)
		yy = yy + 1900;
	var MM = objD.getMonth() + 1;
	if (MM < 10)
		MM = '0' + MM;
	var dd = objD.getDate();
	if (dd < 10)
		dd = '0' + dd;
	var hh = objD.getHours();
	if (hh < 10)
		hh = '0' + hh;
	var mm = objD.getMinutes();
	if (mm < 10)
		mm = '0' + mm;
	var ss = objD.getSeconds();
	if (ss < 10)
		ss = '0' + ss;
	var str = yy + "-" + MM + "-" + dd + " " + hh + ":" + mm + ":" + ss;
	return str;
}

function getLocaleDate() {
	var objD = new Date();
	var yy = objD.getYear();
	if (yy < 1900)
		yy = yy + 1900;
	var MM = objD.getMonth() + 1;
	if (MM < 10)
		MM = '0' + MM;
	var dd = objD.getDate();
	if (dd < 10)
		dd = '0' + dd;
	var str = yy + "-" + MM + "-" + dd;
	return str;
}

function getLocaleTime() {
	var objD = new Date();
	var hh = objD.getHours();
	if (hh < 10)
		hh = '0' + hh;
	var mm = objD.getMinutes();
	if (mm < 10)
		mm = '0' + mm;
	var ss = objD.getSeconds();
	if (ss < 10)
		ss = '0' + ss;
	var str = hh + ":" + mm + ":" + ss;
	return str;
}

function getFormatDate(yy, MM, dd) {
	if (yy < 1900)
		yy = yy + 1900;
	if (MM < 10)
		MM = '0' + MM;
	if (dd < 10)
		dd = '0' + dd;
	var str = yy + "-" + MM + "-" + dd;
	return str;
}

function getFormatTime(hh, mm, ss) {
	if (hh < 10)
		hh = '0' + hh;
	if (mm < 10)
		mm = '0' + mm;
	if (ss < 10)
		ss = '0' + ss;
	var str = hh + ":" + mm + ":" + ss;
	return str;
}

function autoLoginUser() {
	var url = DfServer + 'rest/user/session';
	var data = {
		'email' : UserName,
		'password' : PWD
	};
	var loginState = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json;charset=utf-8',
		url : url,
		data : JSON.stringify(data),
		cache : false,
		async : false,
		type : 'POST',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName
		},
		success : function(response) {
			setCookie('GEO_USERNAME', UserName);
			setCookie('GEO_Token', response.session_id);
			loginState = true;
		},
		error : function(response) {
			var msg = "用户密码出错!";
			if (response.content && response.content.data && response.content.data.error) {
				msg += "详细信息：" + response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			alert(msg);
		}
	});
	return loginState;
}

function getRecordsByFilter(database, table, filter, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	var data = null;
	if (filter == null || filter == "" || filter == undefined)
		data = null;
	else
		data = {
			filter : filter
		};
	if (async == null)
		async = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		url : url,
		data : data,
		cache : false,
		async : async,
		type : 'GET',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined' && error) {
				error(msg);
			}
		}
	});
}

function getRecordsByFilterOrder(database, table, filter, order, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	var data = null;
	if (!filter)
		filter = "";
	data = {
		filter : filter,
		order : order
	};
	if (async == null)
		async = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		url : url,
		data : data,
		cache : false,
		async : async,
		type : 'GET',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined') {
				error(msg);
			}
		}
	});
}

function getPageRecordsByFilterOrder(database, table, filter, order, pageSize, pageIndex, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	var data = null;
	if (!filter)
		filter = "";
	var offset = pageSize * pageIndex;
	data = {
		filter : filter,
		order : order,
		include_count : true,
		limit : pageSize,
		offset : offset
	};
	if (async == null)
		async = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json; charset=utf-8',
		url : url,
		data : data,
		cache : false,
		async : async,
		type : 'GET',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined') {
				error(msg);
			}
		}
	});
}

function addRecords(database, table, data, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	if (data == null || data == "" || typeof data == 'undefined')
		return;
	if (async == null)
		async = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json;',
		url : url,
		data : JSON.stringify(data),
		async : async,
		type : 'POST',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined') {
				error(msg);
			}
		}
	});
}

function updateRecords(database, table, data, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	if (data == null || data == "" || typeof data == 'undefined')
		return;
	if (async == null)
		async = false;
	$.ajax({
		dataType : 'json',
		contentType : 'application/json;',
		url : url,
		data : JSON.stringify(data),
		cache : false,
		async : async,
		type : 'PUT',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined') {
				error(msg);
			}
		}
	});
}

function deleteRecordsByGuid(database, table, filter, success, error, async) {
	var url = DfServer + 'rest/' + database + '/' + table;
	var token = getCookie('GEO_Token');
	if (filter == null || filter == "" || typeof filter == 'undefined')
		return;
	if (async == null)
		async = false;
	var data = {
		filter : filter
	};
	$.ajax({
		dataType : 'json',
		contentType : 'application/json;',
		url : url,
		data : JSON.stringify(data),
		cache : false,
		async : async,
		type : 'DELETE',
		timeout : 300000,
		headers : {
			"X-DreamFactory-Application-Name" : AppName,
			"X-DreamFactory-Session-Token" : token
		},
		success : function(response) {
			if ( typeof success !== 'undefined') {
				success(response);
			}
		},
		error : function(response) {
			var msg = "发生未知错误";
			if (response.content && response.content.data && response.content.data.error) {
				msg = response.content.data.error[0].message;
			}
			msg = msg.replace(/&quot;/g, '"').replace(/&gt;/g, '>').replace(/&lt;/g, '<').replace(/&amp;/g, '&').replace(/&apos;/g, '\'');
			if ( typeof error !== 'undefined') {
				error(msg);
			}
		}
	});
}

function getLocaleTimeFileName() {
	var objD = new Date();
	var yy = objD.getYear();
	if (yy < 1900)
		yy = yy + 1900;
	var MM = objD.getMonth() + 1;
	if (MM < 10)
		MM = '0' + MM;
	var dd = objD.getDate();
	if (dd < 10)
		dd = '0' + dd;
	var hh = objD.getHours();
	if (hh < 10)
		hh = '0' + hh;
	var mm = objD.getMinutes();
	if (mm < 10)
		mm = '0' + mm;
	var ss = objD.getSeconds();
	if (ss < 10)
		ss = '0' + ss;
	var str = yy + MM + dd + hh + mm + ss;
	return str;
}

function uploadPictures(pics, belongGuid, modelId) {
	var url = MultimediaUrl + 'page/upload.aspx';
	for (var i = 0; i < pics.length; i++) {
		api.ajax({
			url : url,
			method : 'post',
			timeout : 100,
			dataType : 'json',
			returnAll : false,
			data : {
				files : {
					Filedata : pics[i]
				}
			}
		}, function(ret, err) {
			if (err && err.statusCode == '200') {
				Guid2(function(guid) {
                    SaveFileBusinessInfo(belongGuid, modelId, err.body, guid);
                });
			}
		});
	}
}

function SaveFileBusinessInfo(belongGuid, modelId, fileName, guid) {
	var typeCode = 'B4183E44-82A9-45E9-A2A5-FCDD8CC12580';
	var index = fileName.lastIndexOf('.');
	var length = fileName.length;
	var ext = 'jpg';
	if (index > 0) {
		ext = fileName.substring(index + 1, length);
	}
	var fullName = getLocaleTimeFileName() + "." + ext;
//	var guid = Guid();
	var fileInfo = {
		fileTempName : fileName,
		storageMethod : '文件夹',
		description : '',
		fullname : fullName,
		creator : getCookie('QcqfMan'),
		guid : guid,
		typeCode : typeCode
	};

	var businessInfo = {
		typeCode : typeCode,
		modelId : modelId,
		belongObjectGuid : belongGuid,
		fileinfoGuid : guid,
	};
	var fileInfoUrl = MultimediaUrl + "AjaxHandler.ashx?class=FileImageInfoAjax&method=addFileImage";
	var businessInfoUrl = MultimediaUrl + "AjaxHandler.ashx?class=BusinessInfoAjax&method=AddBusinessInfo";
	
	var ajax1 = $.ajax({
		url : fileInfoUrl,
		async : false,
		data : fileInfo,
//		success : function(json) {
//			showMsg('fileInfo保存成功！');
//		},
//		error : function(e) {
//			console.log("保存FileImageInfo出错：" + e);
//		},
//		cache : false
	});
	
	var ajax2 = $.ajax({
		url : businessInfoUrl,
		async : false,
		data : businessInfo,
//		success : function(json) {
//			showMsg('BusinessInfo保存成功！');
//		},
//		error : function(e) {
//			console.log("保存BusinessInfo出错：" + e);
//		},
//		cache : false
	});
	$.when(ajax1,ajax2).done(function(res1,res2){
		showMsg('图片上传成功');
	});
}

function getServerTime() {
	var time = null;
	//从服务器获取时间
	getRecordsByFilter('qcqf', 'vwTime', null, function(response) {
		if (response.record != null && response.record.length > 0) {
			time = response.record[0].now;
		}
	}, null, false);
	if (time == null) {
		alert("获取服务器时间失败！");
		return null;
	}
	return time;
}

//短信发送
function sendMsg(content, mobiles) {
	if (content == null || content == "" || mobiles == null || mobiles.length < 1)
		return null;
	var rlt = null;
	var url = MsgServerUrl + "AjaxHandler.ashx?class=ShortMsgAjax&method=SendMsg";
	var json = {
		MsgContent : content,
		Mobiles : mobiles
	}
	$.ajax({
		url : url,
		async : false,
		timeout : 300000,
		data : {
			json : JSON.stringify(json)
		},
		success : function(res) {
			rlt = res;
		},
		error : function(e) {
			rlt = e;
		},
		cache : false
	});
	return rlt;
}